package com.zjw.socket.demo.starter.messageService.service;

import com.zjw.socket.demo.starter.annotation.core.Bean;
import com.zjw.socket.demo.starter.annotation.core.Inject;
import com.zjw.socket.demo.starter.messageService.*;

@Bean
public class MessageEnterService {

  @Inject(query = "MessageTransferService")
  public MessageTransferService messageTransferService;
  @Inject
  public SystemMessageService systemMessageService;
  @Inject(query = "SimpleUserPool")
  public IUserPool userPool;
  public IMessageFadeService messageFadeService;

  public void start() {
    messageFadeService.fadeServiceInit();
  }

  public void enter(Message message) {
    int type = message.getType();

    //根据通道获取connectSession，
//    String chanel = message.getChanel();
    //这里实际是获得连接
    //在后续解耦过程中，此处应该抽象为与IM_SERVICE的连接
    IConnectSession sender = message.getFromChanel();

    onPreProcess(message, sender);

    //优先系统消息，
    if (systemMessageService.isSystemMessage(type)) {
      systemMessageService.processSystemMessage(message, sender);
      return;
    }
    //转运消息
    messageTransferService.transferTo(message);
    MessageCacheFactory.recycle(message);
  }

  private void onPreProcess(Message message, IConnectSession sender) {
    //service收到就回复类消息
    int processStrategy = message.getProcessStrategy();
    if (MessageProcessStrategy.hasFlag(processStrategy, MessageProcessStrategy.RESPONSE_MESSAGE_IF_SERVICE_ACCEPT_MASK)) {
      Message responseMessage = MessageCacheFactory.obtain();
      responseMessage.setFromId(0);
      responseMessage.setToId(message.getFromId());
      responseMessage.setTime(message.getTime());
      responseMessage.setType(SystemMessageType.RESPONSE_SERVICE_ACCEPT_SENDER);
      responseMessage.setBytes(MessageParser.toByte(message));
      sender.writeMessage(responseMessage);
    }
  }
}
